<template>
  <BaseControlTemplate
    v-show="showImage"
    class="image"
    :class="{
      readonly: pageViewMode !== 'runtime' || readonly,
      full: rowImgLen === 7,
      half: !newParams.imgDirection,
    }"
    :new-params="newParams"
    :page-view-mode="pageViewMode"
    :readonly="readonly"
    :model-value="modelValue"
    :validate-error="validateError"
    :save-dialog-config="saveDialogConfig"
  >
    <div
      v-if="pageViewMode !== 'print'"
      style="display: flex; flex-direction: row"
    >
      <div
        v-for="(item, index) in fileList"
        :key="index"
        class="el-upload-custom-list"
        style="position: relative"
      >
        <el-image
          style="width: 112px; height: 88px; padding-right: 10px"
          class="el-upload-list__item-thumbnail"
          :src="item.baseImg"
          :preview-src-list="imgUrlList"
          @click="clickImage(item.url)"
        >
        </el-image>
        <i
          v-if="pageViewMode !== 'runtime' || !readonly"
          class="el-icon-delete-solid"
          style="
            font-size: 25px;
            color: red;
            position: absolute;
            top: 5px;
            right: 10px;
            z-index: 1;
          "
          @click="removeImg(index)"
        ></i>
        <span
          v-if="pageViewMode === 'runtime' && !readonly"
          class="el-upload-list__item-actions"
        >
          <span
            class="el-upload-list__item-delete"
            @click.stop="handleRemove(item)"
          >
            <img :src="imageDelete" />
          </span>
        </span>
      </div>
    </div>
    <!-- 2023-04-12 姜军
1.因为预览的数据源和上传的数据对象不一致，导致预览无论点击那个图片都从第一张开始预览
2.upload 的数据源从 fileList换成 imgUrlList
3.受影响的图片上传和测试 -->
    <el-upload
      ref="uploadComp"
      class="base-upload"
      name="files"
      multiple
      action
      :headers="headers"
      :show-file-list="pageViewMode === 'print' ? true : false"
      :show-upload-list="false"
      :limit="15"
      :file-list="fileList"
      :list-type="listType"
      :auto-upload="false"
      :accept="accept"
      :on-change="uploadImg"
      :on-exceed="handleExceed"
      :disabled="pageViewMode !== 'runtime' || readonly"
      drag
    >
      <div
        class="el-upload-custom-text"
        :class="{ 'next-row': fileList.length > rowImgLen }"
      >
        <div class="el-upload__text">
          <img :src="require('../../img/updateimg.png')" />
          <span>{{ fileList.length ? "继续上传图片" : "点击上传图片" }}</span>
        </div>
        <div v-if="fileList.length === 0" slot="tip" class="el-upload__tip">
          或将文件拖到这里，单次最多可选15张
        </div>
      </div>
      <template
        v-if="pageViewMode === 'print'"
        slot="file"
        slot-scope="{ file }"
      >
        <el-image
          class="el-upload-list__item-thumbnail"
          :src="file.baseImg"
          :preview-src-list="imgUrlList"
        >
        </el-image>
      </template>
    </el-upload>
    <!-- <el-upload
      ref="uploadComp"
      class="base-upload"
      name="files"
      multiple
      action
      :headers="headers"
      :show-file-list="true"
      :show-upload-list="false"
      :limit="15"
      :file-list="fileList"
      :list-type="listType"
      :auto-upload="false"
      :accept="accept"
      :on-change="uploadImg"
      :on-exceed="handleExceed"
      :disabled="pageViewMode !== 'runtime' || readonly"
      drag
    >
      <div
        class="el-upload-custom-text"
        :class="{ 'next-row': fileList.length > rowImgLen }"
      >
        <div class="el-upload__text">
          <img :src="require('../../img/updateimg.png')" />
          <span>{{ fileList.length ? '继续上传图片' : '点击上传图片' }}</span>
        </div>
        <div v-if="fileList.length === 0" slot="tip" class="el-upload__tip">
          或将文件拖到这里，单次最多可选15张
        </div>
      </div>

      <div slot="file" v-slot="{ file }" class="el-upload-custom-list">
        <el-image
          class="el-upload-list__item-thumbnail"
          :src="file.url"
          :preview-src-list="imgUrlList"
          @click="clickImage(file.url)"
        >
        </el-image>

      </div>
    </el-upload> -->
  </BaseControlTemplate>
</template>

<script>
import mixins from "../../mixins/vue.js";
import { getToken } from "../../utils/auth";
import { uploadImgFile, rotateImg, GetStaticImgInfo } from "@/api/Base";
import { formdataify } from "../../utils/index.js";
import imageDelete from "../../img/image-delete.png";

export default {
  name: "ControlImage",
  mixins: [mixins],
  data() {
    return {
      initialIndex: 0,
      imgShow: true,
      imgUrl: 0,
      imgUrlList: [],
      uploadLoad: false,
      disabled: false,
      uploadImgFile: uploadImgFile,
      imageDelete,
      headers: { Authorization: getToken() },
      fileList: [],
      listType: "picture-card",
      accept: ".jpg,.jpeg,.png",
      previewUrl: "",
      dialogVisible: false,
      picturePath: [],
      newParams: {},
      deg: "0",
      rowImgLen: 6,
      fileList2: [],

      showImage: true,
    };
  },
  watch: {
    // 解决打印时图片大小变化导致的视觉问题
    pageViewMode(newVal, oldVal) {
      if (newVal === "print" || oldVal === "print") {
        this.fileList = [];
        this.$nextTick(() => {
          this.fileList = Object.assign([], this.fileList2);
          this.showImage = newVal === "print" ? this.fileList.length : true;
        });
      }
    },
  },
  created() {
    this.newParams = JSON.parse(JSON.stringify(this.params));
    this.newParams.imgDirection === null && (this.newParams.imgDirection = 0);
    this.fileList = this.newParams.value
      ? this.newParams.value
        .filter((v) => v.includes("http") || v.includes("https"))
        .map((x) => {
          return { url: x + "?n=" + new Date().getMilliseconds() };
        })
      : [];
    this.fileList2 = Object.assign([], this.fileList);
    for (let i = 0; i < this.fileList.length; i++) {
      this.imgDispose(this.fileList[i].url).then((baseImg) => {
        this.fileList[i].baseImg = baseImg;
        this.imgUrlList.push(baseImg);
        this.$forceUpdate();
      });
    }
    // this.imgUrlList = this.fileList.map(
    //   (item) => item.url + "?n=" + new Date().getMilliseconds()
    // );
  },
  methods: {
    removeImg(index) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.imgUrlList.splice(index, 1);
          this.fileList.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    imgDispose(url) {
      return new Promise((resolve, reject) => {
        var imgPath = "";
        const cleanedUrl = url
          .replace("[", "")
          .replace("]", "")
          .replace('"', "");
        const regexPattern = /http:\/\/[^/]+\/[^/]+\/([^?]+)/;
        const matchs = regexPattern.exec(cleanedUrl);
        if (matchs) {
          imgPath = matchs[1];
        } else {
          imgPath = url;
        }
        GetStaticImgInfo(imgPath).then((res) => {
          resolve(res.data);
        });
      });
    },
    clickImage(imgUrl) {
      this.imgUrl = imgUrl;
      this.$nextTick(() => {
        const wrapper = document.getElementsByClassName(
          "el-image-viewer__actions__inner"
        );
        const downImg = document.createElement("i");
        downImg.setAttribute("class", "el-icon-check");
        wrapper[0].appendChild(downImg);
        if (wrapper.length > 0) {
          this.wrapperElem = wrapper[0];
          this.cusClickHandler();
        }
      });
    },

    // 给按钮添加点击事件
    cusClickHandler() {
      this.wrapperElem.addEventListener("click", this.hideCusBtn);
    },
    // 点击事件
    hideCusBtn(e) {
      const className = e.target.className;
      // 旋转照片
      if (
        className === "el-icon-refresh-right" ||
        className === "el-icon-refresh-left"
      ) {
        // console.log(this.num);
        // var imgUrl = this.imgUrl;
        var element = document.getElementsByClassName("el-image-viewer__img");
        var degA = element[0].style.transform.substring(16);
        this.deg = degA.substring(0, degA.length - 4);
        if (this.deg.indexOf("(") !== -1) {
          this.deg = this.deg.substring(2, degA.length - 2);
        }
      }
      // 确认修改
      if (className === "el-icon-check") {
        // 请求后台旋转图片 imgUrl图片路径 angle角度 splitTag url分割标签

        this.$confirm("是否保存设置", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            rotateImg({
              imgUrl: this.imgUrl,
              angle: this.deg,
              splitTag: "img",
              businessType: 50,
            }).then((res) => {
              this.$message({
                type: "success",
                message: res.msg ? res.msg : "修改成功",
              });
              for (var i = 0; i < this.fileList.length; i++) {
                this.fileList[i].url =
                  this.fileList[i].url + new Date().getMilliseconds();
              }
              for (let i = 0; i < this.fileList.length; i++) {
                this.imgDispose(this.fileList[i].url).then((baseImg) => {
                  this.fileList[i].baseImg = baseImg;
                  this.imgUrlList.push(baseImg);
                  this.$forceUpdate();
                });
              }
              // this.imgUrlList = this.fileList.map(
              //   (item) => item.url + "?n=" + new Date().getMilliseconds()
              // );
              this.showImage = false;
              this.$nextTick(() => {
                this.showImage = true;
              });
            });
          })
          .catch(() => {});

        const close = document.querySelector(".el-icon-circle-close");
        close.click();
        // studentDetail(this.stuid.bm_id).then((res) => {
        //   this.form.material = res.data.material;
        // });
      }
    },
    // 上传完成
    uploadImg(info) {
      if (info.status !== "ready") return;
      const fileFormat = this.beforeUpload(info);
      if (!fileFormat) return;
      const obj = {
        businessType: "10",
        file: info.raw,
      };
      const form = formdataify(obj);
      uploadImgFile(form)
        .then((res) => {
          this.uploadLoad = false;
          const data = res.data;
          const url = `${data.protocol}${data.fileDomain}/${data.fileBucket}/${
            data.filePath
          }?n=${new Date().getMilliseconds()}`;
          this.imgDispose(url).then((baseImg) => {
            this.fileList.push({
              url: url,
              baseImg,
            });
            this.fileList2 = Object.assign([], this.fileList);
            this.imgUrlList.push(baseImg);
          });
          this.$forceUpdate();

          // this.imgUrlList = this.fileList.map(
          //   (item) => item.url + "?n=" + new Date().getMilliseconds()
          // );
          this.validateError = false;
        })
        .catch(() => {
          this.uploadLoad = false;
        });
      if (info.status === "fail") {
        this.uploadLoad = false;
        this.$message.error("上传失败");
      }
    },
    // 移除
    handleRemove(imgurl) {
      var index = 0;
      for (var i = 0; i < this.imgUrlList.length; i++) {
        if (this.imgUrlList[i] === imgurl) {
          index = i;
        }
      }

      this.fileList = this.fileList.splice(index, 1);
      this.validateRequired();
    },
    // 预览
    handlePreview(file) {
      if (file.url) {
        this.previewUrl = file.url;
      } else {
        this.previewUrl = this.$base + file.response.data[0];
      }
      this.dialogVisible = true;
    },
    handleClose() {
      this.previewUrl = "";
      this.dialogVisible = false;
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      if (!this.accept) return;
      const fileTypes = this.accept.split(",");
      const type = `.${file.raw?.type.split("/")[1]}`;
      const checkFormat =
        fileTypes.includes(type) || file.type === "image/vnd.microsoft.icon";
      return checkFormat;
    },
    handleExceed() {
      this.$message({
        message: "至多支持15张图片,已超出可选图片最大范围",
        type: "warning",
      });
    },
    customFn() {
      this.rowImgLen = this.rowImgLen === 6 ? 7 : 6;
    },
    validateRequired() {
      if (
        this.pageViewMode !== "runtime" ||
        this.readonly ||
        !this.newParams.required
      ) {
        return;
      }
      this.validateError = this.fileList.length === 0;
    },
    validate() {
      this.newParams.value = this.fileList.map((x) => x.url);
      this.validateRequired();
      return {
        controlValue: this.newParams,
        validateError: this.validateError,
      };
    },
  },
};
</script>
